//
//  WeatherInfoController.m
//  PingShan
//
//  Created by jsmysoft on 16/10/28.
//  Copyright © 2016年 jsmysoft. All rights reserved.
//

#import "WeatherInfoController.h"
#import <CoreLocation/CoreLocation.h>
#import "AFNetworking.h"
#import "ZLCWebView.h"
#import "WeatherModel.h"
#import "WeatherFutureModel.h"
#import "WeatherSkyconModel.h"
#import "WeatherTemperatureModel.h"
#import "WeatherWindModel.h"
#define isiOS8 __IPHONE_OS_VERSION_MAX_ALLOWED>=__IPHONE_8_0

@interface WeatherInfoController ()<UIWebViewDelegate>
//天气
@property (strong, nonatomic) IBOutlet UIButton *weatherBtn;
//卫星
@property (strong, nonatomic) IBOutlet UIButton *satelliteBtn;
//雷达
@property (strong, nonatomic) IBOutlet UIButton *radarBtn;
//创建webView
@property (nonatomic, strong) UIWebView * webView;
//url
@property (nonatomic, copy) NSString *url;
//背景View
@property (strong, nonatomic) IBOutlet UIView *bgView;
//天气View
@property (strong, nonatomic) IBOutlet UIView *weatherView;
//卫星云图View
@property (strong, nonatomic) IBOutlet UIView *CloundView;
//雷达View
@property (strong, nonatomic) IBOutlet UIView *radarView;
//button数组
@property (nonatomic, strong) NSMutableArray *buttonsArr;
//地址
@property (strong, nonatomic) IBOutlet UILabel *locationLabel;
//温度
@property (strong, nonatomic) IBOutlet UILabel *temperatureLabel;
//风速
@property (strong, nonatomic) IBOutlet UILabel *windSpeedLabel;
//pm25
@property (strong, nonatomic) IBOutlet UILabel *pm25Label;
//实时天气数组
@property (nonatomic, strong) NSMutableArray *realTimeWeatherArr;
//实时天气模型
@property (nonatomic, strong) WeatherModel *realWeatherMdoel;
//实时天气图片
@property (strong, nonatomic) IBOutlet UIImageView *realWeatherImg;
//未来天气模型
@property (nonatomic, strong) WeatherFutureModel *futureModel;
//温度数组
@property (nonatomic, strong) NSMutableArray *temperatureArr;
//天气和日期数组
@property (nonatomic, strong) NSMutableArray *skyconArr;
//风速
@property (nonatomic, strong) NSMutableArray *windArr;
//日期集合
@property (strong, nonatomic) IBOutletCollection(UILabel) NSArray *dateCollection;
//天气图片集合
@property (strong, nonatomic) IBOutletCollection(UIImageView) NSArray *imageCollection;
//温度集合
@property (strong, nonatomic) IBOutletCollection(UILabel) NSArray *temperatureCollection;
//天气描述集合
@property (strong, nonatomic) IBOutletCollection(UILabel) NSArray *skyconCollection;
//天气风速集合
@property (strong, nonatomic) IBOutletCollection(UILabel) NSArray *windSpeedCollection;

@end

@implementation WeatherInfoController

//懒加载
- (NSMutableArray *)realTimeArr {
    if (!_realTimeWeatherArr) {
        _realTimeWeatherArr = [NSMutableArray array];
    }
    return _realTimeWeatherArr;
}
- (NSMutableArray *)temperatureArr {
    if (!_temperatureArr) {
        _temperatureArr = [NSMutableArray array];
    }
    return _temperatureArr;
}
- (NSMutableArray *)skyconArr {
    if (!_skyconArr) {
        _skyconArr = [NSMutableArray array];
    }
    return _skyconArr;
}
- (NSMutableArray *)windArr {
    if (!_windArr) {
        _windArr = [NSMutableArray array];
    }
    return _windArr;
}
- (void)viewWillAppear:(BOOL)animated {
    //获取实时天气数据
    [self getRealTimeWeatherData];
    //获取未来四天的数据
    [self getFutureWeatherData];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"气象信息";
    self.weatherBtn.selected = true;
    self.satelliteBtn.selected = false;
    self.radarBtn.selected = false;
    [self.weatherBtn setTitleColor:MainColor forState:UIControlStateSelected];
    self.CloundView.hidden = YES;
    self.radarView.hidden = YES;
    self.buttonsArr = [NSMutableArray arrayWithObjects:_weatherBtn,_radarBtn, _satelliteBtn, nil];
    
}

#pragma mark -- createWebView
- (UIWebView *)createWebView
{
    self.webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height)];
    [self.webView setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight];
    [self.webView setDelegate:self];
    [self.webView setMultipleTouchEnabled:YES];
    [self.webView setAutoresizesSubviews:YES];
    [self.webView setScalesPageToFit:YES];
    [self.webView.scrollView setAlwaysBounceVertical:YES];
    self.webView.scrollView.bounces = NO;
    self.webView.delegate = self;
    return _webView;
}
//请求数据
- (void)getWebViewData:(NSString *)url{
    self.url = url;
    NSURL  *URL = [NSURL URLWithString:self.url];
    [self.webView loadRequest:[NSURLRequest requestWithURL:URL]];
}
#pragma mark -- 获取实时天气数据
//获取AFHTTPRequestOperationManager
- (AFHTTPRequestOperationManager *)getAFHTTPRequestOperationManager {
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    //申明返回的结果是json类型
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    //申明请求的数据是json类型
    manager.requestSerializer=[AFJSONRequestSerializer serializer];
    return manager;
}

- (void)getRealTimeWeatherData {
    AFHTTPRequestOperationManager * manager = [self getAFHTTPRequestOperationManager];
    //如果报接受类型不一致请替换一致text/html或别的application/json
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/html",@"application/json", nil];
    NSString *urlStr = [NSString stringWithFormat:@"%@",@"https://api.caiyunapp.com/v2/j0YjlSf41iaMTGWk/103.9991,28.7024/realtime.json"];
    [manager GET:urlStr parameters:@{} success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSLog(@"responseObject--%@", responseObject);
        if (responseObject != nil) {
            self.realWeatherMdoel = [WeatherModel mj_objectWithKeyValues:responseObject];
            NSLog(@"arr--%@",_realWeatherMdoel);
            //赋值
            [self  setRealWeatherData];
        }
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
    }];
}
#pragma mark -- 实时天气数据赋值
- (void)setRealWeatherData {
    /**给地理位置名称赋值*/
    CLLocationDegrees latitude = [[self.realWeatherMdoel.location objectAtIndex:0] doubleValue];
    CLLocationDegrees longitude = [[self.realWeatherMdoel.location objectAtIndex:1] doubleValue];
    CLLocation * location = [[CLLocation alloc] initWithLatitude:latitude longitude:longitude];
    //    CLLocationCoordinate2D coordinate = location.coordinate;
    CLGeocoder * geocoder = [[CLGeocoder alloc] init];
    [geocoder reverseGeocodeLocation:location completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
        CLPlacemark * placeMark = [placemarks firstObject];
        self.locationLabel.text = placeMark.name;
    }];
    self.temperatureLabel.text = [NSString stringWithFormat:@"%@: %@%@",@"温度",self.realWeatherMdoel.result[@"temperature"],@"℃"];
    self.windSpeedLabel.text = [NSString stringWithFormat:@"%@: %@",@"风速",self.realWeatherMdoel.result[@"wind"][@"speed"]];
    self.pm25Label.text = [NSString stringWithFormat:@"%@: %@",@"pm",self.realWeatherMdoel.result[@"pm25"]];
    NSString * skyconStr = self.realWeatherMdoel.result[@"skycon"];
    if (skyconStr != nil) {
        if ([skyconStr isEqualToString:@"CLEAR_DAY"]){
            self.realWeatherImg.image = [UIImage imageNamed:@"图层-3"];
        } else if ([skyconStr isEqualToString:@"PARTLY_CLOUDY_DAY"]){
            self.realWeatherImg.image = [UIImage imageNamed:@"图层-4"];
        } else if ([skyconStr isEqualToString:@"CLOUDY"]) {
            self.realWeatherImg.image = [UIImage imageNamed:@"图层-12"];
        } else if ([skyconStr isEqualToString:@"RAIN"]) {
            self.realWeatherImg.image = [UIImage imageNamed:@"图层-13"];
        } else if ([skyconStr isEqualToString:@"SNOW"]) {
            self.realWeatherImg.image = [UIImage imageNamed:@"图层-14"];
        } else if ([skyconStr isEqualToString:@"WIND"]) {
            self.realWeatherImg.image = [UIImage imageNamed:@"图层-18"];
        }
    }

}

#pragma mark -- 获取未来四天数据
- (void)getFutureWeatherData {
    AFHTTPRequestOperationManager *manager = [self getAFHTTPRequestOperationManager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/html",@"application/json", nil];
    NSString * urlStr = [NSString stringWithFormat:@"%@",@"https://api.caiyunapp.com/v2/j0YjlSf41iaMTGWk/103.9991,28.7024/forecast.json"];
    [manager GET:urlStr parameters:@{} success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSLog(@"responseObject--%@",responseObject);
        self.futureModel = [WeatherFutureModel mj_objectWithKeyValues:responseObject];
        self.temperatureArr = [WeatherTemperatureModel mj_objectArrayWithKeyValuesArray:self.futureModel.result[@"daily"][@"temperature"]];
        NSLog(@"temperature--%@",self.temperatureArr);
        self.skyconArr = [WeatherSkyconModel mj_objectArrayWithKeyValuesArray:self.futureModel.result[@"daily"][@"skycon"]];
        self.windArr = [WeatherWindModel mj_objectArrayWithKeyValuesArray:self.futureModel.result[@"daily"][@"wind"]];
        NSLog(@"wind--%@",self.windArr);
        //设置未来天气的数据
        [self setFutureWeatherData];
    
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
    }];
}
#pragma mark -- 设置未来天气的数据
- (void)setFutureWeatherData {
    for (int i = 1; i < self.skyconArr.count; i ++) {
        UILabel * timeLabel = self.dateCollection[i - 1];
        WeatherSkyconModel * skyModel = self.skyconArr[i];
        timeLabel.text = [NSString stringWithFormat:@"%@",skyModel.date];
        UILabel * skyconLabel = self.skyconCollection[i - 1];
        skyconLabel.text = [NSString stringWithFormat:@"%@",skyModel.value];
        UIImageView * imageView = self.imageCollection[i - 1];
        if (skyconLabel.text != nil) {
            if ([skyconLabel.text isEqualToString:@"CLEAR_DAY"]){
                imageView.image = [UIImage imageNamed:@"图层-3"];
            } else if ([skyconLabel.text isEqualToString:@"PARTLY_CLOUDY_DAY"]){
                imageView.image = [UIImage imageNamed:@"图层-4"];
            } else if ([skyconLabel.text isEqualToString:@"CLOUDY"]) {
                imageView.image = [UIImage imageNamed:@"图层-12"];
            } else if ([skyconLabel.text isEqualToString:@"RAIN"]) {
                imageView.image = [UIImage imageNamed:@"图层-13"];
            } else if ([skyconLabel.text isEqualToString:@"SNOW"]) {
                imageView.image = [UIImage imageNamed:@"图层-14"];
            } else if ([skyconLabel.text isEqualToString:@"WIND"]) {
                imageView.image = [UIImage imageNamed:@"图层-18"];
            }
        }
        
    }
    for (int i = 1; i < self.temperatureArr.count; i ++) {
        UILabel * temperatureLabel = self.temperatureCollection[i - 1];
        WeatherTemperatureModel * tempModel = self.temperatureArr[i];
        temperatureLabel.text = [NSString stringWithFormat:@"%@"@"~"@"%@"@"℃",tempModel.min,tempModel.max];
    }
    for (int i = 1; i < self.windArr.count; i ++) {
        UILabel * windLabel = self.windSpeedCollection[i - 1];
        WeatherWindModel * windModel = self.windArr[i];
        windLabel.text = [NSString stringWithFormat:@"最大风速:"@"%@",windModel.max[@"speed"]];
    }
    
}

//头部按钮点击事件
- (IBAction)headBtnClick:(UIButton *)sender {
    //遍历头部所有的按钮,,先把他们的selected全部设为NO;
    for (UIButton *tempBtn in self.buttonsArr) {
        tempBtn.selected = NO;
    }
    //然后把选中的按钮的selected设为YES;  KO~
    sender.selected = YES;
    if (sender.tag == 101) {
        self.weatherView.hidden = NO;
        self.CloundView.hidden = YES;
        self.radarView.hidden = YES;
        [self.weatherBtn setTitleColor:MainColor forState:UIControlStateSelected];
        [self.satelliteBtn setTitleColor:[UIColor darkGrayColor] forState:UIControlStateNormal];
        [self.radarBtn setTitleColor:[UIColor darkGrayColor] forState:UIControlStateNormal];
    } else if (sender.tag == 102) {
        UIWebView * webView = [self createWebView];
        [self.CloundView addSubview:webView];
        self.weatherView.hidden = YES;
        self.CloundView.hidden = NO;
        self.radarView.hidden = YES;
        [self.satelliteBtn setTitleColor:MainColor forState:UIControlStateSelected];
        [self.weatherBtn setTitleColor:[UIColor darkGrayColor] forState:UIControlStateNormal];
        [self.radarBtn setTitleColor:[UIColor darkGrayColor] forState:UIControlStateNormal];
        self.url = @"http://m.nmc.cn/publish/satellite/fy2.htm";
        [self getWebViewData:self.url];
    } else if (sender.tag == 103) {
        UIWebView * webView = [self createWebView];
        [self.radarView addSubview:webView];
        self.weatherView.hidden = YES;
        self.CloundView.hidden = YES;
        self.radarView.hidden = NO;
        [self.radarBtn setTitleColor:MainColor forState:UIControlStateSelected];
        [self.weatherBtn setTitleColor:[UIColor darkGrayColor] forState:UIControlStateNormal];
        [self.satelliteBtn setTitleColor:[UIColor darkGrayColor] forState:UIControlStateNormal];
        self.url = @"http://m.nmc.cn/publish/radar/chinaall.html";
        [self getWebViewData:self.url];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
